![]() |
|
|
|
|
|||||||
| Forums | Portal | Register | Forum Rules | FAQ | Contribute | Members List | Arcade | Search | Today's Posts | Mark Forums Read |
| Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts here. |
|
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| How to compare a field value of a same column? | gobinath | Shell Programming and Scripting | 5 | 05-28-2008 09:15 PM |
| replace the column values. | charandevu | Shell Programming and Scripting | 6 | 04-01-2008 11:21 PM |
| how to read the column and print the values under that column | gemini106 | Shell Programming and Scripting | 6 | 03-28-2008 04:05 AM |
| How to check Null values in a file column by column if columns are Not NULLs | Mandab | Shell Programming and Scripting | 7 | 03-15-2008 06:57 AM |
| replace a column values with the first value in column | sumeet | UNIX for Advanced & Expert Users | 3 | 02-06-2007 10:13 AM |
|
|
Submit Tools | LinkBack | Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Need help with switching field/column values
Hi all, I need some help on switching field/column values. For example I have a file name data.txt which contains:
a b a b a b and I want to switch a and b and save it to the same file. the file data.txt then will have: b a b a b a The problem is, well, I know how to switch field values in awk, but it's not gonna modify the file itself. I could just output the result to another file and change the file name, but now I want to modify the file data.txt directly. Is there any way to do it? And I would like to know if vi can do that. Thank you very much. |
| Forum Sponsor | ||
|
|
|
#2
|
|||
|
|||
|
I know Perl has ways to re-write the file in-place, but I'm not too familiar with swapping fields.
Probably something like 's/(.*) (.*)/\2 \1/g' |
|
#3
|
|||
|
|||
|
Woo, that works great! Thank you so much.
|
|
#4
|
|||
|
|||
|
If you wanted to automate the process, stick the commands into a file and have vim make the changes using the ex mode.
For example: commandFile: :% s/\(.*\) \(.*\)/\2 \1/g :1,$ print <-- not needed, but helpful to show you the changes :wq datafile: a b a b a b vim -e -s < commandFile datafile -e = ex mode -s = silent mode Note that the changes get written back to the datafile You could also call "ex" directly to do this: ex < commandFile datafile |
|
#5
|
|||
|
|||
|
awk
Hi,
I think awk is easy to handle this. Try follow one. Code:
echo "a b" | awk '{print $2" " $1}'
|
|
#6
|
|||
|
|||
|
if all you really have is "a b" for each line:
perl -pi.bak -e 'chomp;$_=reverse($_)."\n"' yourfile.txt |
|
#7
|
|||
|
|||
|
Code:
cat data.txt | rev |
|||
| Google The UNIX and Linux Forums |