【问题标题】:Change FS and RS to parse newline char [duplicate]更改 FS 和 RS 以解析换行符 [重复]
【发布时间】:2016-10-30 10:42:16
【问题描述】:

我在 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

请问您知道如何进行吗? :/

【问题讨论】:

  • 您究竟是如何尝试更改它们的?
  • 它们是真正的新行还是字符串“\n”?什么是`tab[]?一个 awk 数组?
  • 这里我试过了: config=cat $1 tab=($(echo $config | awk ' BEGIN { RS = "\n" ; FS = ""}; { for (i = 1 ; i

标签: awk newline fs


【解决方案1】:

问题是,无论你如何在 awk 中解析文件,它都会作为一个简单的字符串返回到 shell。

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

为了将返回的字符串分配给数组,您需要将shell的IFS设置为换行符,或者将行一一分配给数组项(您可以使用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

【讨论】:

  • 不确定,没有得到我期望的结果,我猜没有任何东西打印到标签中
  • 我用工作代码和解释编辑了我的答案
猜你喜欢
  • 2011-04-27
  • 2012-07-20
  • 2020-06-03
  • 2018-07-06
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多