使用sed,将特定字符串下面的行的部分写入两个不同的变量

时间:2014-08-14 17:55:05

标签: regex linux sed text-processing

我有包含以下内容的文本文件,“DOB”仅在文件中提及一次....

DOB
Female 1/1/1963

在列出的示例中,我需要将Female存储在名为VarGender的变量中,并将日期存储在名为VarDOB的字段中。我想结束......

VarGender=Female
VarDOB=1/1/1963

以下内容将返回DOB下方的整行。我可以使用一些帮助将每一半的线都变成正确的变量。

sed -n '/DOB/{n;p}' file.txt

非常感谢。

6 个答案:

答案 0 :(得分:2)

强制性awk替代方案:

awk '! /DOB/ { printf "VarGender=%s\nVarDOB=%s\n",$1,$2 }' file.txt

答案 1 :(得分:0)

{ read; read VarGender VarDOB; } < file.txt

这将在文件中的某处读取:

while P=$VarGender; read VarGender VarDOB && [[ $P != DOB ]]; do :; done < file.txt

答案 2 :(得分:0)

你可以使用while while循环:

while read -r line; do
    [[ "$line" == "DOB" ]] && dob=1 && continue
    ((dob==1)) && dob=0 && read VarGender VarDOB <<< "$line"
done < file

echo "$VarGender :: $VarDOB"
Female :: 1/1/1963

答案 3 :(得分:0)

更简单的while循环。

while read field1 therest; do
  if [ ${field1:-x} = DOB ]; then
    read VarGender VarDOB;
    break;
  fi;
done < file

答案 4 :(得分:0)

$ arr=( $(awk 'f{print; exit} /DOB/{f=1}' file) )
$ VarGender="${arr[0]}"
$ VarDOB="${arr[1]}"
$ echo "$VarGender"
Female
$ echo "$VarDOB"
1/1/1963

答案 5 :(得分:0)

您只需在打印前修改缓冲区:

$ sed -n '/DOB/{n;s/^\([^ ]\+\).*/\1/;p}' file.txt
Female
$ sed -n '/DOB/{n;s/^[^ ]\+ \(.*\)/\1/;p}' file.txt
1/1/1963