简体   繁体   English

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

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

I have a file containing lines similar too ... 我也有一个包含相似行的文件...

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

I want to take the last string at the end of each line and put it at the start of the line, for example .. 我想将最后一个字符串放在每行的末尾,并将其放在行的开头,例如..

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

Any help greatly appreciated 任何帮助,不胜感激

Thanks. 谢谢。

Use this for example: 例如使用此:

$ 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

It sets / as field separator, so that the filename is the last field. 它将/设置为字段分隔符,以便文件名是最后一个字段。 Then it is a matter of printing accordingly. 然后是相应的打印问题。

Or safer, to handle filenames with spaces and globbing chars, etc ( thanks Ed Morton !): 或更安全的是,使用空格和通配符等处理文件名( 感谢Ed Morton !):

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

In bash you can loop through the lines and make use of basename : 在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 returns the strip and suffix from filenames, so that from a name like /path/like/this.sh you get this.sh . basename返回文件名中的带和后缀,因此从/path/like/this.sh类的名称中获得this.sh

And the one through GNU sed , 然后通过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

Text after last / symbol are fetched and stored into a group. 最后/符号后的文本被提取并存储到组中。 Again in the replacement part, "cp group wholeline" helps to give the above output. 同样在替换部分中,“ cp group wholeline”有助于给出上述输出。

Using bash parameter substitution : 使用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

From the link: 从链接:

${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.

these three sed one-liners should work too, but awk would be more straightforward: 这三个sed单行代码也应该起作用,但是awk会更简单:

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

and

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

and

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

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

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