繁体   English   中英

在其中带有正斜杠的文件中使用awk

[英]Using awk in a file that has forward slashes in it

我也有一个包含相似行的文件...

/home/test/gp/fish/lib/fish.eye
/home/test/gp/fish/kerf/pl/teeth.eye

我想将最后一个字符串放在每行的末尾,并将其放在行的开头,例如..

cp fish.eye /home/test/gp/fish/lib/fish.eye
cp teeth.eye /home/test/gp/fish/kerf/pl/teeth.eye

任何帮助,不胜感激

谢谢。

例如使用此:

$ awk -F/ '{print "cp", $NF, $0}' your_file
cp fish.eye /home/test/gp/fish/lib/fish.eye
cp teeth.eye /home/test/gp/fish/kerf/pl/teeth.eye

它将/设置为字段分隔符,以便文件名是最后一个字段。 然后是相应的打印问题。

或更安全的是,使用空格和通配符等处理文件名( 感谢Ed Morton !):

awk -F/ '{printf "cp \"%s\" \"%s\"\n", $NF, $0}' your_file

在bash中,您可以循环浏览各行并利用basename

while IFS= read -r line
do
    echo "cp" "$(basename "$line")" "$line"
    #printf "cp %s %s\n" "$(basename "$line")" "$line" <-- this also works
done < your_file

basename返回文件名中的带和后缀,因此从/path/like/this.sh类的名称中获得this.sh

然后通过GNU sed

$ sed -r 's/^.*\/(.*)$/cp \1 &/' file
cp fish.eye /home/test/gp/fish/lib/fish.eye
cp teeth.eye /home/test/gp/fish/kerf/pl/teeth.eye

最后/符号后的文本被提取并存储到组中。 同样在替换部分中,“ cp group wholeline”有助于给出上述输出。

使用bash 参数替换

while read -r line; do
    echo "cp ${line##*/} $line" 
done < file
cp fish.eye /home/test/gp/fish/lib/fish.eye
cp teeth.eye /home/test/gp/fish/kerf/pl/teeth.eye

从链接:

${parameter##word} 

The word is expanded to produce a pattern just as in filename expansion 
(see Filename Expansion). If the pattern matches the beginning of the expanded value 
of parameter, then the result of the expansion is the expanded value of parameter 
with the shortest matching pattern (the ‘#’ case) or the longest matching pattern 
(the ‘##’ case) deleted.

这三个sed单行代码也应该起作用,但是awk会更简单:

sed 's/.*/& &/;s#[^ ]*/#cp #' file

sed 'h;s#.*/#cp #;G;s/\n/ /' file

sed 's#.*/\(.*\)#cp \1 &#' file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM