0

In order to make a school project easier, I want to append a delimiter to each line beginning with a capital letter with a bash script. Could anyone help me out? I've tried reading the file line-by-line in tandem with the case command but it doesn't work I don't really understand what I'm doing. This is what i have so far: (I'm new to scripting, don't flame me)

#!/bin/bash
input=/home/user/file
while IFS= read -r var
do
        case [A-Z]
                sed 's/^/#/' file
done
forrestal
  • 3
  • 1
  • It should be faster/better to simply do sed '/^[A-Z]/s/^/#/' "$input". –  Jun 30 '20 at 07:16

1 Answers1

2

You don't use shell loops to process text. Processing text is done by text processing tools which are the ones that process their input one line at a time:

#! /bin/sh -
input=/home/user/file
sed 's/^[[:upper:]]/#&/' < "$input"

Would insert a # before an uppercase letter found at the start (^) of each line of $input.

Here, uppercase letter is as determined by the locale. It will include the ABCDEFGHIJKLMNOPQRSTUVWXYZ English letters, and possibly things like Á, Ź, or Π if present.

If you wanted to restrict to ABCDEFGHIJKLMNOPQRSTUVWXYZ only, you'd write:

sed 's/^[ABCDEFGHIJKLMNOPQRSTUVWXYZ]/#&/' < "$input"

[A-Z] itself may match on about anything depending on the locale. You'll find systems where it matches on abcdefghijklmnopqrstuvwxy (not z) as well. On most systems, it would match on Á, but not Ź if present in the locale's charmap. It could even match on sequences of characters (multi-character collating elements like the Hungarian Ddzs).