Regex 使用sed或awk时,如何将当前行的末尾与指定的字符进行匹配?
我有一个文本文件中的文件位置列表。例如:Regex 使用sed或awk时,如何将当前行的末尾与指定的字符进行匹配?,regex,linux,bash,sed,awk,Regex,Linux,Bash,Sed,Awk,我有一个文本文件中的文件位置列表。例如: /var/lib/mlocate /var/lib/dpkg/info/mlocate.conffiles /var/lib/dpkg/info/mlocate.list /var/lib/dpkg/info/mlocate.md5sums /var/lib/dpkg/info/mlocate.postinst /var/lib/dpkg/info/mlocate.postrm /var/lib/dpkg/info/mlocate.prerm
/var/lib/mlocate
/var/lib/dpkg/info/mlocate.conffiles
/var/lib/dpkg/info/mlocate.list
/var/lib/dpkg/info/mlocate.md5sums
/var/lib/dpkg/info/mlocate.postinst
/var/lib/dpkg/info/mlocate.postrm
/var/lib/dpkg/info/mlocate.prerm
我想做的是使用sed或awk从每行的末尾开始读取,直到第一个正斜杠为止(即,从每个文件地址中选择实际的文件名)
我对sed和awk的语法都有点动摇。有人能帮忙吗?使用命令
basename
$~hawk] basename /var/lib/mlocate
mlocate
这里确实不需要使用
sed
或awk
,只需使用usbasename
IFS=$'\n'
for file in $(cat filelist); do
basename $file;
done
如果您想使用目录部分,请使用dirname
我也支持“basename”,但为了完整起见,这里有一个awk one-liner:
$ sed -e 's!^.*/!!' locations.txt
mlocate
mlocate.conffiles
mlocate.list
mlocate.md5sums
mlocate.postinst
mlocate.postrm
mlocate.prerm
awk -F/ 'NF>0{print $NF}' <file.txt
awk-F/'NF>0{print$NF}'Pure Bash:
while read -r line
do
[[ ${#line} != 0 ]] && echo "${line##*/}"
done < files.txt
读取时-r行
做
[${line}!=0]&&echo“${line}{line}*/}”
done
编辑:排除空行。@OP,您可以使用awk
awk -F"/" 'NF{ print $NF }' file
NF表示字段数,$NF表示获取最后一个字段的值
还是用贝壳
while read -r line
do
line=${line##*/} # means longest match from the front till the "/"
[ ! -z "$line" ] && echo $line
done <"file"
读取时-r行
做
line=${line###*/}表示从前面到“/”的最长匹配
[!-z“$line”]&回音$line
如果文件
包含路径列表,则Thius也会这样做
$ xargs -d '\n' -n 1 -a file basename
这是一个不那么聪明、笨拙的巴肯版本:
sed -e 's/^.*\/\([^\/]*\)$/\1/'
为了完整性,也要去掉空行{if(NF>0)print$NF}
;)+1basename一次只适合一个文件;要处理文件中的名称,sed或awk也可以工作,如果不是更好的话。Cool。有没有可能将空行
的测试压缩到{}
中?很多文件中都有空格names@ghost我添加了IFS
行。这会将我从空格中遍历的列表中分隔条目的字符更改为“$”…”语法的\n
+1。我从来没有遇到过这样的情况(经过这么多年的抨击之后),它会在带有空格的文件上断开-d'\n'防止在空格上断开行
sed -e 's/^.*\/\([^\/]*\)$/\1/'