Linux 使用sed或awk搜索包含特殊字符的行
我想知道Linux中是否有命令可以帮助我找到以“*”开头并包含特殊字符“|”的行 比如说Linux 使用sed或awk搜索包含特殊字符的行,linux,awk,sed,Linux,Awk,Sed,我想知道Linux中是否有命令可以帮助我找到以“*”开头并包含特殊字符“|”的行 比如说 * Date | Auteurs 只需使用: grep -ne '^\*.*|' "${filename}" 或者如果要使用sed: sed -n '/^\*.*|/{=;p}' "${filename}" | sed '{N;s/\n/:/}' 或(gnu)awk等效物(需要对管道进行反斜杠): 其中: ^:行首 \*:文字* *:零个或多个通用字符(非换行符) |:文字管道 NB:
* Date | Auteurs
只需使用:
grep -ne '^\*.*|' "${filename}"
或者如果要使用sed
:
sed -n '/^\*.*|/{=;p}' "${filename}" | sed '{N;s/\n/:/}'
或(gnu)awk
等效物(需要对管道进行反斜杠):
其中:
:行首^
:文字\*
*
:零个或多个通用字符(非换行符)*
:文字管道|
“${filename}”
:我假设您正在脚本中使用命令,目标文件以双引号变量“${filename}”传递。在shell中,只需使用文件的实际名称(或路径)
更新(行号)
修改上述命令以获得匹配行的行号。使用grep
可以简单地添加-n
开关:
grep -ne '^\*.*|' "${filename}"
我们得到如下输出:
81806:* Date | Auteurs
要从sed
和awk
获得完全相同的输出,我们必须稍微复杂化命令:
awk '/^\*.*\|/{print NR ":" $0}' "${filename}"
# the = print the line number, p the actual match but it's on two different lines so the second sed call
sed -n '/^\*.*|/{=;p}' "${filename}" | sed '{N;s/\n/:/}'
我已经更新了答案,也打印了行号,告诉我它是否像你期望的那样工作。它工作了,谢谢
awk '/^\*.*\|/{print NR ":" $0}' "${filename}"
# the = print the line number, p the actual match but it's on two different lines so the second sed call
sed -n '/^\*.*|/{=;p}' "${filename}" | sed '{N;s/\n/:/}'