I have a file with 130 fields separated by semicolons. I want to rearrange them in some fashion.
Consider the below example:
File Sample.txt:
1;2;3;4;8;5;6;7;9;10;11;
11;12;13;14;18;15;16;17;19;20;21;
Required output (file req_op.txt):
1;2;3;4;5;6;7;8;9;10;11;
11;12;13;14;15;16;17;18;19;20;21;
Notice that the eighth element is misplaced. All I am doing is to streamline the line. The problem is there are 121 fields and so I am not able to use concise AWK commands to do this text manipulation in single line for the whole file.
I have tried the below and it is working. Can you suggest a more efficient or more readable solution? I request you to please also explain your solution.
Each field can have numbers and strings separated by space/string containing $
, #
, etc.
#!/bin/bash
file="sample.txt"
while read -r line
do
array=($(echo "$line" | sed 's/;/ /g'))
printf -v first '%s;' "${array[@]:0:4}"
printf -v last '%s;' "${array[@]:8:12}"
printf -v second '%s;' "${array[@]:5:3}"
printf -v third '%s;' "${array[@]:4:1}"
echo "${first}${second}${third}${last}" >> req_op.txt
done < $file
The actual number of fields:
Input:
1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35|36|37|38|39|40|41|42|43|44|45|46|47|48|49|50|51|52|53|54|55|56|57|58|59|60|61|62|63|64|65|66|67|68|69|70|71|72|73|74|75|76|77|78|79|80|81|82|83|84|85|86|87|88|89|90|91|92|93|94|95|96|97|98|99|100|101|102|103|104|105|106|107|108|109|110|111|112|113|114|115|116|117|118|119|120|121|122|123|124|125|126|127|128|129|130|131|132|133|134|135|136|137|143|138|139|140|141|142|144|145|146|147|148|149|150|151|152|153|154|155|156|157|158|159|160|161|162
output:
1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35|36|37|38|39|40|41|42|43|44|45|46|47|48|49|50|51|52|53|54|55|56|57|58|59|60|61|62|63|64|65|66|67|68|69|70|71|72|73|74|75|76|77|78|79|80|81|82|83|84|85|86|87|88|89|90|91|92|93|94|95|96|97|98|99|100|101|102|103|104|105|106|107|108|109|110|111|112|113|114|115|116|117|118|119|120|121|122|123|124|125|126|127|128|129|130|131|132|133|134|135|136|137|138|139|140|141|142|143|144|145|146|147|148|149|150|151|152|153|154|155|156|157|158|159|160|161|162
I modified sed command shared by @Quasímodo; and now its working as expected.
sed -E 's~(([^\|]*\|){137})([^\|]*\|)(([^\|]*\|){5})~\1\4\3~' sample.txt
perl -F';' -lne 'print join ";", sort { $a <=> $b } @F' sample.txt
– Jul 27 '20 at 05:00|
is a regex metacharacter, so it would require a complete refactory in all the answers. It's totally OK to open another question if you cannot adapt the answers to your real need. And don't worry, we all were new here once. – Quasímodo Jul 27 '20 at 16:04