0

I have the following file on my Ubuntu machine:

file.txt

http://example.com/https:/www.google.com
http://test.example.com
https://www.example.com
https://www.click.example.com
http://example.com
http://test.example.com
https://www.example.com/https:/www.google.com
https://www.click.example.com

I want the output in the new file:

new_file.txt

https://www.example.com
https://www.click.example.com
https://www.example.com/https:/www.google.com
https://www.click.example.com

I am using sed as shown below, but it includes in the output file all lines that contain https anywhere in the line.

sed -n '/https/p' file.txt > new_file.txt

I want to limit the search to the first 5 characters: if it finds the https in the first 5, then print the line and otherwise skip it.

Thanks.

1

sed uses basic regex (BRE) as default to search for text, so you can use its syntax:

^

Matches the null string at beginning of the pattern space, i.e. what appears after the circumflex must appear at the beginning of the pattern space.

So, for you:

sed -n '/^https/p' file.txt > new_file.txt

Or use grep:

grep '^https' file.txt > new_file.txt
2
  • That is called regular expression (regex), a text matching syntax. You should dig into it, it's great stuff.
    – pLumo
    May 11 at 9:20
  • 1
    There is no magic... Just like h matches an h in a line, ^ matches the beginning of a line.
    – pLumo
    May 11 at 9:25

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.