![如何使用参数 Grep 配置文件中的第二个单词?](https://linux22.com/image/136030/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E5%8F%82%E6%95%B0%20Grep%20%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%E7%AC%AC%E4%BA%8C%E4%B8%AA%E5%8D%95%E8%AF%8D%EF%BC%9F.png)
目前,我正在构建一个脚本,根据参数在配置文件中 grep 区域记录,然后使用该输出创建一个文本文件,并读取该输出文件中的源文件路径。现在我需要再传递一个参数,例如模块,因为它必须创建一个文本文件。
我的脚本:
#!/bin/bash
SOURCE_CONF="./test.properties"
#input region name
region="$1"
echo $region
cwd=$(pwd)
calu=$(grep $region test.properties > ab.txt)
IFS=$'\n'
#loop to read the config one line at a time
while read p; do
echo $p
a=($(echo "$p" | tr '|' '\n'))
echo "Region is:" "${a[0]}"
echo "path is:""${a[3]}"
path="${a[3]}"
#remove white space before path
echo $cwd
NO_LEAD_SPACE="$(echo -e $path | tr -d '[:space:]')"
echo "path is:"$NO_LEAD_SPACE
# change to path spacified in the config file
sh -c 'cd $NO_LEAD_SPACE && echo "in the subshell" && echo $pwd && echo "exit subshell" && exec pwd'
echo $cwd
echo "--------------------"
done < ab.txt
echo "abc"
我的配置文件:
region | Module |country code | filepath |filename
APJ | WDMD | MYS |/c/Users/vattikun/desktop | MYS*ADPGV*.XML
APJ | WDED | EUR|/c/Users/vattikun/desktop/Payroll Support | EUR*ADPGV*.XML
APJ | WDMD | RER|/c/Users/vattikun/desktop/Payroll Support | RER*ADPGV*.XML
APJ | WDJD | EYZ|/c/Users/vattikun/desktop/Payroll Support | EYZ*ADPGV*.XML
EMA | WDMD | AUS|/c/Users/vattikun/desktop | AUS*ADPGV*.XML
EMA | WDMD | AYS| /c/Users/vattikun/desktop | AYS*ADPGV*.XML
AMS | WDMD |ITI| /c/Users/vattikun/desktop | ITI*ADPGV*.XML
AMS |WDMD |AYS| /c/Users/vattikun/desktop | AYS*ADPGV*.XML
ETIME | WDMD |ADP /c/Users/vattikun/desktop | ADP_WDET_JOBCODE*.XML
ETIME | WDMD |AEP| /c/Users/vattikun/desktop | AEP_WDET_JOBCODE*.XML
答案1
要回答您提出的具体问题,请使用一种跳过一个字段的模式开始搜索表达式:
module="$2"
/bin/grep "^[^|]*| *${module}\\>" test.properties
分解一下:
^ Start of line
[^|]* 0 or more non-separator characters
| A field separator
* 0 or more spaces
${module} Switch from single- to double-quotes to interpolate variable name
\\> End of a word ("\\>" becomes '\>' when shell parses it)
但你最好使用类似awk
or 的东西perl
:
awk -F' *\\| *' -v module="$module" '$2 == module' test.properties
从长远来看,最好使用 CSV 等众所周知的格式以及与之配合使用的工具。