I'm trying to write a script to edit the format of a text file. I got a file with coordinates in the form
x: 123
y: 456
x: 789
y: 012
...
but need it in the form
123 456 i
789 012 i
...
Kind of like here Edit text format with shell script , just the other way round and a little more ;)
Do u guys have any ideas how i can achieve this?
A simple bash script using a counter to toggle printing after read of every 2 lines can suit your need. Just pass the data file as argument 1:
#!/bin/bash
declare -i cnt=0
while read -r line || [ -n "$line" ]; do
array+=( ${line##* } ) # read values into array
((cnt++)) # increase counter
if [ "$cnt" -eq 2 ]; then # if count = 2
printf "%s %s i\n" "${array[0]}" "${array[1]}" # print both array values
cnt=0 # reset count to 0
unset array # unset array
fi
done <"$1"
output
123 456 i
789 012 i
You could use something like this:
awk 'NR>1&&NR%2{print a[1],a[2],"i";i=0}{a[++i]=$2}END{print a[1],a[2],"i"}' file
The array a
contains the contents of the previous two lines. Ignoring the first line, when the line number is odd (ie when NR%2
is 1), print the last two lines, followed by "i". At the end, print the last two lines.
Testing it out:
$ awk 'NR>1&&NR%2{print a[1],a[2],"i";i=0}{a[++i]=$2}END{print a[1],a[2],"i"}' file
123 456 i
789 012 i
You could use awk
:
$ awk '$1 == "x:"{line=$2}$1 == "y:"{line=line FS $2 FS "i"; print line}' file
123 456 i
789 012 i
Alternatively, a read
loop:
while read -ra line; do
case ${line[0]} in
x:)
new_line=${line[1]}
;;
y:)
new_line+=" ${line[1]} i"
echo $new_line
;;
esac
done < file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.