1

if I have a txt file with an item in each line for example, fruits.txt.

apples
oranges
bananas
cherries

How can I use a bash command line/s to convert it into another txt file that has an enumerated id corresponding to a particular fruit, to say fruitids.txt.

item {
  id: 1
  name: 'apples'
}

item {
  id: 2
  name: 'oranges'
}

item {
  id: 3
  name: 'bananas'
}

item {
  id: 4
  name: 'cherries'
}
1
  • you can do it with awk, Commented Jan 5, 2018 at 11:35

3 Answers 3

2

Awk solution:

awk '{ printf "item {\n  id: %d\n  name: \047%s\047\n}\n",NR,$1 }' fruits.txt > fruitids.txt

The final fruitids.txt contents:

item {
  id: 1
  name: 'apples'
}
item {
  id: 2
  name: 'oranges'
}
item {
  id: 3
  name: 'bananas'
}
item {
  id: 4
  name: 'cherries'
}
Sign up to request clarification or add additional context in comments.

Comments

1

try:

nl fruits.txt |awk '{print "item {\n" "\t id:" $1"\n \t name:" $2 "\n}"}' > fruitsid.txt

Comments

1

Another solution with pure bash:

c=0
while read i; do 
    c=$((c+1))
    echo -e "item {\n  id: $c \n  name: '$i'\n}"
done < <(cat fruits.txt) >> fruitsid.txt

One-liner:

c=0; while read i; do c=$((c+1)) && echo -e "item {\n  id: $c \n  name: '$i'\n}" ; done < <(cat fruits.txt) >> fruitsid.txt

Output:

item {
  id: 1 
  name: 'apples'
}
item {
  id: 2 
  name: 'oranges'
}
item {
  id: 3 
  name: 'bananas'
}
item {
  id: 4 
  name: 'cherries'
}

1 Comment

bash one-liners are really hard to read: please add some newlines

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.