1. In one of the text files in all even lines move the first word of the line to the end of the line. Lines containing only one word are not changed.

  2. In one of the text files, delete the second line ending in a - (minus) character.

Use the commands head, tail, sed, pr, etc., except for awk. Do not use more than one auxiliary file. As a last resort, you can use for, while, and other constructs with justification.

  • @Mike, I wanted to clarify with this example one of the aspects of sed. Regarding the relationship : I tried to find out, but I didn’t figure it out to the end. - mymedia
  • I came across such a condition of the problem (only small ones are mentioned about sed there, and the labels refer to the question), and I didn’t try to be smart about ÂŻ_ () _ / ÂŻ - mymedia
  • is already - mymedia
  • Of course, he will literally find this line. but who will search for such a phrase? unless the one who received the exact same task. I've asked "sed modification of even lines" I found the answer. just not yours. And in general, I meant the search right here on the site. for example, I am interested in all sorts of tricks on sed, I’ll enter [sed] in the search here - Mike

1 answer 1

  1. sed -i 'n;s/\(\w\+\)\W*\(.\+\)/\2 \1/' file.txt

    This script for sed consists of two commands (well, heaps of slashes, it's over) and runs like this:

    • The utility starts working from the first line (which turns out to be odd).
    • The first team applies to it. n - display the current line and go to the next.
    • Then the second (even) string is processed. s/.../\2 \1/ - replacement by a regular expression.
    • In the regular schedule, there are two capture groups (in parentheses, preceded by backslashes). \w\+ matches the first word in the string,. .\+ matches the rest of the string. Between these groups there is a \W* - it means a set of delimiters between words.
    • In the wildcard string, the group numbers are mentioned in the reverse order to swap words.
    • Then sed goes to the next line (which is odd) and executes the script again.
  2. sed -i '2{/-$/d}' file.txt

    Unlike the previous one, this script begins with the address — the line number — to which the command is applied. The command, in turn, is a new block of commands — a sub-script, so to speak — which also begins with the address — a regular expression. This time, the regular is simpler and checks that there is a minus at the end of the line. Then the “delete” command follows - just d

For all commands and syntax, see the sed (1) manual.