I want sed
to give me a single line output irrespective of whether the matched pattern is found and substituted, or even if there is no pattern match, with same command options.
我希望sed为我提供一行输出,不管是否找到并替换匹配的模式,或者即使没有模式匹配,使用相同的命令选项。
1. echo "700K" | sed -n 's/[A-Z]//gp' // gives one output
2. echo "700" | sed -n 's/[A-Z]//gp' // no output
Is there any way in sed i can get a single output for second case without removing the "-n" option, forcing it to print the input irrespective of substitution made or not?
在sed中,是否有任何方法可以在不删除“-n”选项的情况下为第二种情况获取单个输出,从而迫使它打印输入,而不考虑是否进行了替换?
2 个解决方案
#1
2
It is not clear for me why you need to keep the -n
option but if you really do need to keep it you can use the following sed
command:
我不清楚为什么需要保留-n选项,但如果确实需要保留,可以使用以下sed命令:
echo "700" | sed -n 's/[A-Z]//g;p'
this will first make the substitution if possible then print the line.
如果可能的话,这将首先进行替换,然后打印行。
output:
输出:
#2
1
You don't need to mess with all these sed options. Use sed in it's simpliest format which will make a substitution if pattern is found:
您不需要把所有这些sed选项搞得一团糟。在最简单的格式中使用sed,如果找到模式,将进行替换:
$ echo "700K" | sed 's/[A-Z]//g'
700
$ echo "700" | sed 's/[A-Z]//g'
700
$ sed --version
sed (GNU sed) 4.4
$ sed 's/[A-Z]//g' <<<$'700\n700K\n500\n3500A'
700
700
500
3500
#1
2
It is not clear for me why you need to keep the -n
option but if you really do need to keep it you can use the following sed
command:
我不清楚为什么需要保留-n选项,但如果确实需要保留,可以使用以下sed命令:
echo "700" | sed -n 's/[A-Z]//g;p'
this will first make the substitution if possible then print the line.
如果可能的话,这将首先进行替换,然后打印行。
output:
输出:
#2
1
You don't need to mess with all these sed options. Use sed in it's simpliest format which will make a substitution if pattern is found:
您不需要把所有这些sed选项搞得一团糟。在最简单的格式中使用sed,如果找到模式,将进行替换:
$ echo "700K" | sed 's/[A-Z]//g'
700
$ echo "700" | sed 's/[A-Z]//g'
700
$ sed --version
sed (GNU sed) 4.4
$ sed 's/[A-Z]//g' <<<$'700\n700K\n500\n3500A'
700
700
500
3500