[英]How can i read specific line and specific field using Bash?
我有這個文件,我只想獲取testme =的值,以便我可以執行其他操作。 但是,這引發了很多局面,實際上還無法使其正常工作。
#!/bin/bash
for i in $(cat /var/tmp/test.ini); do
# just one output i need: value1
grep testme= $i
done
; comments
testme=value1
; comments
testtwo=value2
怎么樣
#!/bin/bash
grep 'testme=' /var/tmp/test.ini | awk -F= '{ print $2 }'
或者只是使用bash
#!/bin/bash
regex='testme=(.*)'
for i in $(cat /var/tmp/test.ini);
do
if [[ $i =~ $regex ]];
then
echo ${BASH_REMATCH[1]}
fi
done
我檢查了您的代碼,問題出在您的for循環中。
您實際上讀取了文件的每一行,並將其提供給grep,這是不正確的。 我猜你有很多錯誤行
沒有相應的文件和目錄
(或類似的東西)。
您應該給grep您的文件名。 (沒有for循環)
例如
grep "testme=" /var/tmp/test.ini
grep -v '^;' /tmp/test.ini | awk -F= '$1=="testme" {print $2}'
grep刪除注釋,然后awk找到該變量並打印其值。 或者,在單個awk行中包含相同內容:
awk -F= '/^\s*;/ {next} $1=="testme" {print $2}' /tmp/test.ini
這個怎么樣?
$ grep '^testme=' /tmp/test.ini | sed -e 's/^testme=//'
value1
我們找到該行,然后刪除前綴,僅保留該值。 Grep會為我們進行迭代,無需明確。
awk可能是正確的工具,但是由於該問題似乎暗示您僅想使用shell,因此可能需要類似以下內容:
while IFS== read lhs rhs; do if test "$lhs" = testme; then # Here, $rhs is the right hand side of the assignment to testme fi done < /var/tmp/test.ini
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.