Linux

我怎樣才能簡化這個?

  • March 7, 2021

你能幫我簡化這個腳本嗎?

這可行,但我認為有一種更簡單的方法可以做到這一點,但我找不到。

文件:

Car Brand:Mercedes | Country:Germany | Car Model:300 SL | Year:04-1960
Car Brand:Lamborghini | Country:Italy | Car Model:Miura | Year:10-1970
Car Brand:Aston Martin | Country:UK | Car Model:DBS | Year:12-1965
Car Brand:Ford | Country:United States of America | Car Model:GT40 | Year:09-1966

輸出:

1:Mercedes:Germany:300 SL:61:xxx
2:Lamborghini:Italy:Miura:51:xxx
3:Aston Martin:UK:DBS:56:xxx
4:Ford:United States of America:GT40:55:xxx

1,2,3,4是行號;61、52、56、55(當年-當年,忽略月份),xxx保險公司(總是一樣,這部分停止工作)

腳本:

line=$(awk '{print NR}' file.txt)
brand=$(sed 's/.*Brand:\(.*\) | Country.*/\1/' file.txt)
country=$(sed 's/.*Country:\(.*\) | Year.*/\1/' file.txt)
sed 's/.*Year:\(.*\) | Car.*/\1/; s/^...//' file.txt > cars.txt
age=$(awk -v age="$(date +%Y)" '{print age - $1}' cars.txt)
model=$(sed 's/.*Model:\(.*\)*/\1/' file.txt)
echo "$(paste <(echo "$line") <(echo "$brand") <(echo "$country") <(echo "$age") <(echo "$model") -d ':')" > cars.txt
# sed -i 's/$/:xxx/' cars.txt
cat cars.txt

謝謝

使用任何 awk:

$ awk -v yr="$(date +'%Y') " -F' *[:|-] *' -v OFS=':' '{print NR, $2, $4, $6, yr-$9, "xxx"}' file
1:Mercedes:Germany:300 SL:61:xxx
2:Lamborghini:Italy:Miura:51:xxx
3:Aston Martin:UK:DBS:56:xxx
4:Ford:United States of America:GT40:55:xxx

以上假設:,|-只能出現在範例中顯示的位置。如果 a-可以出現在品牌名稱(例如Mercedes-Benz)或輸入中的其他位置,則將上述內容調整為:

awk -v yr=$(date +%Y) -F' *[:|] *' -v OFS=':' '{sub(/.*-/,"",$8); print NR, $2, $4, $6, yr-$8, "xxx"}' file

例如:

$ cat file
Car Brand:Mercedes-Benz | Country:Germany | Car Model:300 SL | Year:04-1960
Car Brand:Lamborghini | Country:Italy | Car Model:Miura | Year:10-1970
Car Brand:Aston Martin | Country:UK | Car Model:DBS | Year:12-1965
Car Brand:Ford | Country:United States of America | Car Model:GT40 | Year:09-1966
$ awk -v yr=$(date +%Y) -F' *[:|] *' -v OFS=':' '{sub(/.*-/,"",$8); print NR, $2, $4, $6, yr-$8, "xxx"}' file
1:Mercedes-Benz:Germany:300 SL:61:xxx
2:Lamborghini:Italy:Miura:51:xxx
3:Aston Martin:UK:DBS:56:xxx
4:Ford:United States of America:GT40:55:xxx

如果除了您顯示的位置之外還有任何其他內容,那麼請修復您的範例以更真實地代表您的真實數據:|

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