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
    Commented Jun 11, 2021 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 Commented Jun 11, 2021 at 14:24
  • What's weird is that in regular ViM editor on the same file the command works Commented Jun 11, 2021 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
    Commented Jun 11, 2021 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 $.) Commented Jun 11, 2021 at 14:33

1 Answer 1

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
    Commented Jun 14, 2021 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 Commented Jun 14, 2021 at 14:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .