0

I'm trying to move a certain ViM command into a Linux Bash script. In ViM the command is

:g/^SOMEWORD$/d

To delete any lines containing only some word and nothing else.

When I move it into a bash script it doesn't work anymore

vim -e -s /tmp/file.txt << EOF
    :g/^SOMEWORD$/d
    :update
    :quit
EOF

Escaping the $ doesn't seem to make a difference, is there another way to use the $ in this type of scenario or am I missing something else?

vim -e -s /tmp/file.txt << EOF
    :g/^SOMEWORD\$/d
    :update
    :quit
EOF
7
  • 2
    Are you sure the lines contain just SOMEWORD and nothing else? Does the file have *nix style newlines?
    – choroba
    Jun 11 '21 at 14:16
  • Yeah can't reproduce this - even unescaped $ works for me (perhaps because /d isn't a legal variable name?). Replacing vim -e -s /tmp/file.txt with a simple cat confirms the $ is being passed through the heredoc Jun 11 '21 at 14:24
  • What's weird is that in regular ViM editor on the same file the command works Jun 11 '21 at 14:25
  • Are you sure the problem is the $? if you run the script without the $ does it then delete lines containing SOMEWORD anywhere on the line?
    – mattb
    Jun 11 '21 at 14:32
  • If you single-quote the starting EOF it will avoid interpretation/evaluation of things that look like variables. So vim -e -s /tmp/file.txt << 'EOF'. Please try this and see if it helps. (At any event it will avoid the need for \$ instead of $.)
    – roaima
    Jun 11 '21 at 14:33
0

I don't understand why but editing the file directly in ViM was treating it as a Unix file but editing through the here-doc was treating it as a DOS file. I found this really handy tool that fixed the issue though

`yum install dos2unix`
dos2unix ./filename.txt

This looks like it makes the file compliant with Unix file standards

2
  • Maybe you used a Windows Editor to create the file. This would insert CR+LF instead of LF only as a Unix Editor would do.
    – Bodo
    Jun 14 '21 at 12:31
  • Yes I did. I'm just stumped as to why regular ViM was happy with it and it only failed when doing it with the vim -e -s method Jun 14 '21 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.