我有這樣一行:
輸入檔案1
如何讓 bash 讀取該行并直接復制“file1.txt”的內容來代替該行?或者,如果它看到:INPUT file2在一行中,放入 `file2.txt" 等。
我能做的最好的事情就是使用很多tr命令將檔案粘貼在一起,但這似乎是一個過于復雜的解決方案。
'sed' 也用字串替換行,但我不知道如何輸入檔案的全部內容,替換時可能有數百行。
uj5u.com熱心網友回復:
看起來很簡單awk。您可能希望以不同方式/更優雅地處理錯誤,但是:
$ cat file1
Line 1 of file 1
$ cat file2
Line 1 of file 2
$ cat input
This is some content
INPUT file1
This is more content
INPUT file2
This file does not exist
INPUT file3
$ awk '$1=="INPUT" {system("cat " $2); next}1' input
This is some content
Line 1 of file 1
This is more content
Line 1 of file 2
This file does not exist
cat: file3: No such file or directory
uj5u.com熱心網友回復:
一個 perl 單行,使用 CPAN 模塊Path::Tiny
perl -MPath::Tiny -pe 's/INPUT (\w )/path("$1.txt")->slurp/e' input_file
用于perl -i -M...就地編輯檔案。
uj5u.com熱心網友回復:
不是最有效的方法,但作為練習,我制作了一個檔案來編輯 namedx和幾個名為t1&的輸入源t2。
$: cat x
a
INPUT t2
b
INPUT t1
c
$: while read k f;do sed -ni "/$k $f/!p; /$k $f/r $f" x;done< <( grep INPUT x )
$: cat x
a
here's
==> t2
b
this
is
file ==> t1
c
是的,空行在 INPUT 檔案中。
但是,這將sed重復您的基本檔案。給出
的awk解決方案更好,因為它只通讀一次。
uj5u.com熱心網友回復:
如果你想在純 Bash 中做到這一點,這里有一個例子:
#!/usr/bin/env bash
if (( $# < 1 )); then
echo "Usage: ${0##*/} FILE..."
exit 2
fi
for file; do
readarray -t lines < "${file}"
for line in "${lines[@]}"; do
if [[ "${line}" == "INPUT "* ]]; then
cat "${line#"INPUT "}"
continue
fi
echo "${line}"
done > "${file}"
done
保存到檔案并像這樣運行:(./script.sh input.txt其中input.txt包含與INPUT <file>陳述句混合的文本的檔案)。
uj5u.com熱心網友回復:
sed 解決方案類似于 awk 給出了erlier:
$ cat f
test1
INPUT f1
test2
INPUT f2
test3
$ cat f1
new string 1
$ cat f2
new string 2
$ sed 's/INPUT \(.*\)/cat \1/e' f
test1
new string 1
test2
new string 2
test3
Bash 變體
while read -r line; do
[[ $line =~ INPUT.* ]] && { tmp=($BASH_REMATCH); cat ${tmp[1]}; } || echo $line
done < f
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/323976.html
上一篇:如何在bash中轉義轉義字符?
