如何用另一個文件的第一行取代一個文件的某些特定內容?

如何用另一個文件的第一行取代一個文件的某些特定內容?

我有兩個文件:one.txtsample.txt

one.txt有以下內容:

AAAA
BBBB
CCCC
DDDD

sample.txt有一些具體內容如下:

>>XXXXXXX<<

我怎麼能夠:

  1. one.txt將“XXXXXXX”替換為?
  2. one.txt刪除?的第一行
  3. 重命名one.txtAAAA.txt

在linux命令列中?

在此輸入影像描述

答案1

這是一種方法:

## save the first line of one.txt in the variable $string
string=$(head -n1 one.txt)
## delete the first line of one.txt
sed -i '1d' one.txt
## replace the Xs in `>>XXXXX<<` with the contents of `$string` 
## and save as the new file "$string.txt" (AAAA.txt)
sed "s/>>XXXXXXX<</>>$string<</" sample.txt > $string.txt

>>XXXXXX<<請注意,這假設的任何行上僅出現一次sample.txt。如果每行可以有多個,則上面的命令將僅替換每行上的第一個。若要替換所有這些,請使用以下命令:

sed "s/>>XXXXXXX<</>>$string<</g" sample.txt > $string.txt

您原來的問題在每行末尾都有空格one.txt。如果您的真實檔案就是這種情況,並且您需要在新增到 之前刪除空格sample.txt,請使用以下命令:

string=$(head -n1 one.txt | sed 's/ *$//')

然後與上面相同的命令。

相關內容