[bash] sed awk中使用變數

bash, sed, awk, variable

sed與awk是常用來過濾與比對字串用的內建功能

awk負責處理"行"

sed負責處理"列"

我們在使用時會常搭配變數使用

1. sed搭配變數

先建立一個data1.txt的文字檔,輸入下列資料

line1
line2
line3
line4
line5

透過sed搭配變數輸出每一列資料

# Calculate how many words
my_data_count=`cat data1.txt | wc -w`

# Use sed with variable
for ((i=1; i<=${my_data_count}; i++ )); do
    sed -n "${i}"p data1.txt
done

執行結果

line1
line2
line3
line4
line5

2. awk搭配變數

awk使用變數時,比sed複雜一點,需要先將變數存起來才能使用

例如: awk -v my_var=${variable}

# man awk or awk --help 查看說明
Usage: awk [POSIX or GNU style options] -f progfile [--] file ...
Usage: awk [POSIX or GNU style options] [--] 'program' file ...
POSIX options:		GNU long options: (standard)
	-f progfile		--file=progfile
	-F fs			--field-separator=fs
# 使用變數請看這邊
	-v var=val		--assign=var=val

先建立一個data2.txt的文字檔,輸入下列資料

word1 word2 word3 word4 word5

透過awk搭配變數輸出每一行資料

# Calculate how many words
my_data_count2=`cat data2.txt | wc -w`

# Use awk with variable
for ((i=1; i<=${my_data_count2}; i++ )); do
    awk -v parameter=${i} '{print ${parameter}}' data2.txt
done

執行結果

word1
word2
word3
word4
word5