0

I want to write a file using echo command. The echo commend will get data from anther file.

Here is the echo command:

echo '{
       name: $name
       id: $seq
       }

I have a txt file:

customer 1
customer 2
customer 3

So I want to generate a file doing echo and replace $name from fist line from the txt file.

And then replace $seq start with 1.

This is the file i want.

{
       name: customer 1
       id: 1
       }
{
       name: customer 2
       id: 2
       }
{
       name: customer 3
       id: 3
       }

While reading first line, the ID should be 1, while reading second line the ID should be 2`

1
  • show where do $name and $seq come from? Your current echo approach is not optimal Mar 6, 2018 at 13:08

2 Answers 2

3

try

 awk '{printf "{\n\tname: %s\n\tid: %d\n\t}\n",$0,NR}' file.txt

where

  • printf will skip line, add tab and format string.

for id: argument, you can either use second field in your sample file, or generate one from line number (that is NR (Number of Record) value).

0
2

If you want a proper JSON formatted output:

jq -Rs 'split("\n") |
        .[0:-1]     |
        [ foreach .[] as $customer ( 0; .+1; { name: $customer, id: . } ) ]' ./file

or, shorter,

$ jq -Rs '[ foreach split("\n")[0:-1][] as $customer ( 0; .+1; { name: $customer, id: . } ) ]' ./file

With -Rs we read unformatted raw text as single string of characters. This is split on newlines into an array with split("\n") and since we get an empty value at the end of the array we remove it with .[0:-1] (this selects all elements from the first to the second to last).

With the same input data as in the question, we now have

[
  "customer 1",
  "customer 2",
  "customer 3"
]

We then iterate over the values of this array with each element in $customer and the iterator in . and construct an array of objects with name and id keys accordingly.

The result is

[
  {
    "name": "customer 1",
    "id": 1
  },
  {
    "name": "customer 2",
    "id": 2
  },
  {
    "name": "customer 3",
    "id": 3
  }
]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .