AWK更改FS和RS以解析换行符

时间:2016-06-28 08:08:15

标签: bash shell awk newline fs

我在shell脚本中使用awk来解析文件。 我的问题被标记为另一个的副本,但我想使用awk而我没有找到相同的问题

以下是文件格式:

    Hi everyone I'm new\n
    Can u help me please\n
    to split this file\n
    with awk ?\n

我希望结果:

tab[0]=Hi everyone I'm new
tab[1]=Can u help me please
tab[2]=to split this file
tab[3]=with awk ?

所以我尝试更改FS和RS值以尝试获得我想要的但没有成功。在这里我尝试了:

config=`cat $1`
tab=($(echo $config | awk '
{
  for (i = 1; i < (NF); i++)
    print $i;
}'))

我得到了什么:

Hi
everyone
I'm
new
Can
u
help
me
please
to
split
this
file
with
awk

你知道怎么办吗? :/

1 个答案:

答案 0 :(得分:0)

问题是,无论你在awk中解析文件,它都会以简单的字符串形式返回shell。

AWK将文件拆分为记录(以\ n结尾的行),记录进一步拆分为字段(默认情况下由FS,空格分隔)。

为了将返回的字符串分配给数组,您需要将shell的IFS设置为换行符,或者将这些行逐个分配给数组项(您可以使用NR过滤记录,然后使用NR要求您使用AWK多次读取文件。

您最好的做法是在AWK中打印记录并使用复合赋值将它们分配给bash数组,并将IFS设置为换行符

#/bin/bash

declare -a tab
IFS='
'
# Compount assignment: array=(words)
# Print record: { print } is the same as { print $0 }
# where $0 is the record and $1 ... $N are the fields in the record
tab=($(awk '{ print }' file))
unset IFS

for index in ${!tab[@]}; do
  echo "${index}: ${tab[index]}"
done
# Output:
# 0: Hi everyone I'm new
# 1: Can u help me please
# 2: to split this file
# 3: with awk ?

请注意,awk几乎不会被使用,应该用简单的cat替换。