複数行を含むexample.txtファイルがあります。
Larry is funny!
Funny, I've no glue!
Look here!
Tom has no pants.
The underpants are in the drawer.
Pants are in the closet!
任意の4行のファイルでファイルを生成した後
sed -n '=' example.txt | shuf | head -3 > line_numbers.txt
line_numbers.txtの行番号に次のものが含まれているとします。
1
3
6
line_numbers.txtの各行にWORDという単語を追加してexample.txtを編集したいと思います。これには、「パンツ」(「アンダーパンツ」などの部分単語の代わりに)という完全な単語が含まれています。
どうすればいいですか?
example.txtがこのように見えるようにしたい
Larry is funny!
Funny, I've no glue!
Look here!
Tom has no pants.
The underpants are in the drawer.
Pants are in the closet!WORD
編集する:
完全な単語だけを見つけるには、source_wordを次のように書く必要があります\<source_word\>
。
他の考えられる例:
次の行を含む他のファイルがあります。
I love apples.
You hate pineapples.
Apple pie is delicious.
Why do you do not like eating an apple?
We prefer pears to apples.
How many apples do you want to eat?
I have to bake three apple pies for sunday.
3つのランダムな行番号を含むリストがあります。
6
2
4
--OK
行に完全な単語が含まれている場合にのみ、各行の末尾に追加したいと思いますapples
。
出力は次のようになります。
I love apples.
You hate pineapples.
Apple pie is delicious.
Why do you do not like eating an apple?
We prefer pears to apples.
How many apples do you want to eat?--OK
I have to bake three apple pies for sunday.
ベストアンサー1
私も方法があればいいのですが、個人的にはこの複雑な作業がはるかに簡単だとsed
思います。awk
awk 'NR==FNR{a[$1]++; next}
{
s=tolower($0);
if(FNR in a && s~/pants/){$0=$0"WORD"}
}1' line_numbers.txt examples.txt
Larry is funny!
Funny, I've no glue!
Look here!
Tom has no pants.
The underpants are in the drawer.
Pants are in the closet!WORD
awk
GNU(gawk
Linuxシステムのデフォルト)がある場合は、次のようにしてファイルを適切に編集できます。
gawk -i inplace 'NR==FNR{a[$1]++; print; next}
{
s=tolower($0);
if(FNR in a && s~/pants/){$0=$0"WORD"}
}1' line_numbers.txt examples.txt
または、次の内容を失っても大丈夫なら、少し簡単ですline_numbers.txt
。
gawk -i inplace 'NR==FNR{a[$1]++; next}
{
s=tolower($0);
if(FNR in a && s~/pants/){$0=$0"WORD"}
}1' line_numbers.txt examples.txt