Linux 在具有正向斜杠的文件中使用awk

Linux 在具有正向斜杠的文件中使用awk,linux,awk,sed,Linux,Awk,Sed,我也有一个包含类似行的文件 /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,

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

/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
它将
/
设置为字段分隔符,以便文件名是最后一个字段。那么这就是相应的印刷问题

或者更安全地处理带有空格和全局字符的文件名,等等(!):


在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
当IFS=read-r行时
做
回显“cp”“$(basename“$line”)“$line”

#printf“cp%s%s\n”“$(basename“$line”)“$line”和通过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


这三个sed一行程序也应该可以工作,但awk将更简单:

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


+1用于awk方法,但要使其
printf“cp\%s\”%s\“\n”、$NF、$0
,这样它就可以用于包含空格、全局字符等的文件名。bash one中有一些bug,无论何时编写shell循环来解析文本文件,它都是错误的方法,所以我不会使用它。谢谢@EdMorton:)相应地更新。是的,我记得你在另一次告诉我不要在文件中循环,我现在忍不住要用
basename
!在shell中使用
read
时,您需要在IFS=read-r line
时将其编写为
,除非您有一些非常具体的行为,您试图避免设置
IFS=
或使用
-r
,并且完全了解警告和副作用。不设置
IFS=
会导致启用分词,因此它会弄乱空格(例如,删除前导空格和尾随空格),并且不使用
-r
告诉
读取
来解释转义符,例如,输入中的
\t
,将成为变量中的文本制表符,从而产生与输入完全不同的输出。
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 's/.*/& &/;s#[^ ]*/#cp #' file
sed 'h;s#.*/#cp #;G;s/\n/ /' file
sed 's#.*/\(.*\)#cp \1 &#' file