0

I'm using awk in a shell script to parse a file. My question has been marked as duplicate of an other, but I want to use awk and I didn't find the same question

Here is the file format:

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

The result I hope:

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

So I tried to change FS and RS values to tried get what I wanted but without success. Here what I tried:

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

And what I get:

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

Do u know how to proceed please ? :/

codeforester
  • 39,467
  • 16
  • 112
  • 140
FlipperDev
  • 45
  • 4

1 Answers1

1

The problem is that however you parse the file in awk, it's returned to the shell as a simple string.

AWK splits a file into records (line ending in \n), and records are further split into fields (separated by FS, space by default).

In order to assign the returned string to an array, you need to set the shell's IFS to newline, or assign the lines to array items one by one (you can filter the record with NR, which would then require you to read the file several times with AWK).

Your best course of action is to just print the records in AWK and assign them to a bash array using compound assignment, with IFS set to newline character

#/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 ?

Notice that awk is hardly used at all, and should be replaced with simple cat.

Esa Lindqvist
  • 311
  • 2
  • 6