When I try to remove some characters in each line using sed, I want to see what to be removed in advance using sed, what should I do? for example,
I have a source code file like below, and I want to remove the line numbers at the beginnings:
102. for (int i=0; i < args.length; ++i) {
103. if ("-skip".equals(args[i])) {
104. DistributedCache.addCacheFile(new Path(args[++i]).toUri(), conf);
105. conf.setBoolean("wordcount.skip.patterns", true);
106. } else {
107. other_args.add(args[i]);
108. }
109. }
what can I do with sed to test the regexp for what to be removed later using ‘s'(meaning replaced with empty string)? well, for this specific example, what’s right regexp to remove the line numbers. is it possible to replace them with the right indents for this being source code using sed? that would be powerful!
Thanks.
Since Jaypal already gave an answer showing the changes with an ERE, I’ll give one with a BRE:
I also used POSIX character classes, to show another option and because I find them easier to remember.
To see exactly what you’re going to change, there are a couple of reasonable possibilities. You could use the same regex with
grep -o:This will select only the part of the line that matches the regex, just showing the indented line numbers in this case.
Another approach would be to use
sedagain. You can use&to indicate the matching text in the replace string, which lets you indicate the selected regions, e.g. with stars:which gives: