Sed

如何從另一個列表文件創建新的 txt 文件?

  • October 8, 2021

我正在嘗試從具有域列表的文件創建第二個配置文件。

File1 (file1.txt) 內容

example.com  
example.org  
example.net  
.
.
.

我想用這樣的內容自動創建第二個文件(file2.txt)。

blahblahblah /something/example.com  /something/exmaple.org  /something/example.net......

看起來很簡單,但我無法弄清楚。我可以製作一個域列表(file1.txt),我只需要創建第二個文件,我將把它用作配置文件的一部分。

用 sed

sed -n '
   s,^,/something/,
   1s/^/blahblahblah /
   H
   ${g;s/\n/ /gp}
' file1.txt > file2.txt

用 bash

(   printf "blahblahblah" 
   mapfile -t lines < file1.txt
   printf " /something/%s" "${lines[@]}"
   echo 
) > file2.txt

或者

{   printf "blahblahblah" 
   while IFS= read -r line; do printf " /something/%s" "$line"; done < file1.txt
   echo 
} > file2.txt

**awk**方法:

awk 'BEGIN{ printf "blahblahblah" }{ printf " /something/%s", $0 }
    END{ print "" }' file1.txt > file2.txt

引用自:https://unix.stackexchange.com/questions/432184