I made a script that can swap info on two lines using a combination of awk and sed, but was hoping to consolidate the script to make it run faster. If found this script, but can't seem to get it to work in a bash shell. I keep getting the error "Too many {'s". Any help here would be appreciated:
Swapping two lines with sed
Assume, in the following file I want to swap the third with the fifth line:
one
two
five
four
three
six
seven
Then this could be done with the following sed script:
sed -ne '
3!{p;d;}
h;n;:1
4!{N;b1}
G;h;n;p;g;p' numbers
I'm sorry, but I'm new to unix and am not familiar with perl...in that script, where do i tell the script what file to sort...also, how do i tell it which lines to swap?
Awesome! is there any way to make this code dynamic? I wanted to put some shell variables in here...For example, If I wanted to start with line $x instead of 3, I would start by replacing NR==3 with NR=="'"$x"'"...where would I input my variable for line 5?
Right, so now this code switches line "var" (which for this example is set at 3), with a line two below it...but how do I switch line "var" with say another line defined by another variable, say "var2"?...or would this code not be able to do that?...I know I probably should've asked for this caveat at the outset, my apologies.
I understand what that does...but I was hoping to switch lines var with var1. This switches var with var+2 and var1 with var1+2...If this code isn't built for that...then don't worry about trying to modify this code to do that. I was just hoping it was easy to do using this code.
I had trouble getting either of these to work (i'm probably running it in the wrong shell)...I was able to get the latter to work by passing my variables from bash into the awk statement using "'"s...see below modified code.
#!/bin/bash
ln1=3
ln2=5
awk 'NR=="'"$ln1"'", NR=="'"$ln2"'" {
_[++c] = $0
if (NR=="'"$ln2"'" && j = c)
while (++i<=c)
print _[NR~"^("'"$ln1"'"|""'"$ln2"'")$"?j--:i]
next
}1' infile
Basically, the output would just remain the same with no lines being swapped...I looked around and that "-v" command for awk, is only in certain versions of awk, so I might not be able to use it in the version I'm using.
Hi, I'm a newbie in unix script. Currently i'm using script for my daily job. Can anyone here explain in detail above script? I mean the syntax and command line by line. I do understand the script swap the 3rd line with line 10. If i want to swap line no 2 with line no 3, i just need to change variable line=2 and line1=3 right?