簡體   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